<?php

namespace common\components;

use frontend\models\Member;
use \yii\rest\ActiveController;
use yii\web\Request;
use Yii;
use \common\helps\code;
use \common\helps\tools;
use \common\helps\FrontBehavior;
use yii\db\Query;


/**
 * Class FrontBaseController
 * @author hey_heyang(635870453@qq.com)
 *
 * @package \\${NAMESPACE}
 */
class FrontBaseController extends ActiveController
{

    protected $request;//请求对象
    protected $session;//session对象
    public    $pageSize;//数据返回条数
    public    $member_info=[]; //当前登录的用户信息
    public    $no_check_array = [];//是否验证当前控制器方法
    public    $check_group = [];//验证用户是否加入群组
    public    $m, $c, $a;//moduleName, controllerName, actionName


    /**
     * 基础控制器初始化
     * @author hey_heyang(635870453@qq.com)
     */
    public function init(){  // 做初始化处理
        $this->_header();
        $this->request = \Yii::$app->getRequest();
        $this->session = \Yii::$app->getSession();
        $this->no_check_array = FrontBehavior::NoCheck(); //前端动作是否进行登录过滤
        $this->check_group = FrontBehavior::checkGroup(); //验证用户是否加入群组
        parent::init();
    }

    /**
     * 动作验证
     * @param $action
     * @author hey_heyang(635870453@qq.com)
     * @return bool/json
     */
    public function beforeAction($action){
        $this->m = $action->controller->module->id;//moduelName
        $this->c = $action->controller->id;//controllerName
        $this->a = $action->id;//actionName
        $current_query =  $this->c.'/'.$this->a;

        if (in_array($current_query,$this->no_check_array)){
            $this->setMemberInfo();
            return true;
        } else {
            $this->tokenVerify();//此处需要处理前端token，若已登录，则赋值member_info信息
            if(in_array($current_query,$this->check_group)){
                $this->checkToGroup($current_query);
            }
            if (empty($this->member_info)) {
                tools::outPutData(code::$misslogin);   //未登录,返回登录异常，前端跳转登录页面
            }
            return true;
        }
    }

    /*
     * 登录token验证
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function tokenVerify(){
        $headers = Yii::$app->request->headers;
        $request =  Yii::$app->request;
        $redis = Yii::$app->cache;
        $session = Yii::$app->session;
        $token='';
        if(!empty($headers->get('token'))){
            $token =$headers->get('token');
        }elseif(!empty($request->get('token'))){
            $token =$request->get('token');
        }elseif(!empty($request->post('token'))){
            $token =$request->post('token');
        }

        if ($token) {
//            $admin_id = $session->get('member_id');
//            if(empty($admin_id)){
//                $redis->hdel('member_info',$token);
//                echo json_encode($this->returnMsg(code::error('login_error', '请登录')));die;
//            }
            $info = json_decode($redis->hget('member_info', $token),true);
            if(empty($info['id'])){  //用户信息缓存为空
                $member_model = new Member();
                $info=$member_model->find()->select('id,username,mobile,token,head_img,experience,integral,sex,province_id,city_id,birthday,is_auth')->where(['token'=>$token])->asArray()->one();
                if(empty($info)) {
                    echo json_encode($this->returnMsg(code::error('login_error', '用户不存在，请重新登录')));die;
                }else{
                    $redis->hset('member_info',$token, json_encode($info));
                }
            }

            $expire = $redis->get('member' . $info['id']);
            if(empty($expire)){
                $redis->hdel('member_info',$token);
                echo json_encode($this->returnMsg(code::error('login_error', '登录过期，请重新登录')));die;
            }
            $redis->set('member' . $info['id'], $token, 2592000);  //重新赋值用户登录过期时间
            $this->member_info = $info;

        }else{
            echo json_encode($this->returnMsg(code::error('login_error', '请登录!')));die;
        }
        return true;
    }

    /*
     * 群组权限验证
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public function checkToGroup($current_query){
        $member_info = $this->member_info;
        $gmember = new \frontend\models\GroupMember();
        $group = new \frontend\models\Group();
        $postsJoin = new \frontend\models\PostsJoin();
        $posts = new \frontend\models\Posts();
        $request = $this->request;
        $params = $request->bodyParams;

        if ($current_query == 'movie/click-like') {
            if (!empty($params['is_click']) && $params['is_click'] == 'no') {
                return true;
            }
        }
        if(empty($params['posts_id'])){
            echo json_encode($this->returnMsg(code::error('mistake')));die;
        }
        $rat = $posts::findOne(['id' => $params['posts_id'],'status' => 3]);
        if(empty($rat)){
            echo json_encode($this->returnMsg(code::error('','该信息不存在或已被删除')));die;
        }
        $row = $postsJoin::findOne(['posts_id' => $params['posts_id']]);
        if (!empty($row)) {
            $params['group_id'] = $row['group_id'];
        }
        if (!empty($params['group_id'])) {
            $groupInfo = $group::findOne(['id' => $params['group_id']]);
            if(empty($groupInfo)){
                echo json_encode($this->returnMsg(code::error('mistake')));die;
            }
            $res = $gmember::findOne(['member_id' => $member_info['id'], 'group_id' => $params['group_id']]);
            if (empty($res)) {
                $data = [
                    'status'=>223,
                    'msg'=>'没有'.$groupInfo['name'].'群组权限'
                ];
                echo json_encode($this->returnMsg($data));die;
            }
        }
    }

    public function returnMsg($data){
        $res = [
            'success' => true,
            'code' => 200,
            'message' => 'OK',
            'data' => $data,
        ];
        return $res;
    }


    /**
     * 仅处理会员信息数据以便接口在未过滤接口中需要使用会员信息
     * @author hey_heyang
     */
    public function setMemberInfo(){
        $headers = Yii::$app->request->headers;
        $request =  Yii::$app->request;
        $redis = Yii::$app->cache;
        $token='';
        if(!empty($headers->get('token'))){
            $token =$headers->get('token');
        }elseif(!empty($request->get('token'))){
            $token =$request->get('token');
        }elseif(!empty($request->post('token'))){
            $token =$request->post('token');
        }
        if ($token) {
            $info = json_decode($redis->hget('member_info', $token),true);
            if(empty($info['id'])){
                return;
            }
            $expire = $redis->get('member' . $info['id']);
            if(empty($expire)){
                $redis->hdel('member_info',$token);
                return;
            }
            $this->member_info = $info;
        }
        return;

    }


    /**
     * 处理跨域
     * @author hey_heyang
     */
    private function _header()
    {
        header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With, company-id, source, source-url, access-token, store-id");
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Max-Age: 3628800');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
    }

}
